<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="handleExport">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column label="用户编号" prop="userId" min-width="80" />
      <el-table-column label="手机号码" prop="mobile" min-width="120" />
      <el-table-column label="用户昵称" prop="nickname" min-width="100" />
      <el-table-column label="活动名称" prop="activityName" min-width="150" />
      <el-table-column label="商品名称" prop="productName" min-width="150" />
      <el-table-column label="当前阶段" align="center" prop="stage" min-width="100">
        <template #default="scope">
          <el-tag
            :type="getStageTagType(scope.row.stage, scope.row.activityUploadProof, scope.row.activityName, scope.row.hasClosed)"
          >
            {{ getStageText(scope.row.stage, scope.row.activityUploadProof, scope.row.activityName, scope.row.hasClosed) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="打卡规则" align="center" prop="punchCardRule" min-width="100">
        <template #default="scope">
          {{ getPunchCardRuleText(scope.row.punchCardRule) }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        min-width="160"
        :formatter="dateFormatter"
      />
      <el-table-column label="操作" align="center" width="160" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            :disabled="!scope.row.activityName"
            @click="handleView(scope.row)"
          >
            查看
          </el-button>
          <el-button
            v-if="scope.row.isAfterSale"
            link
            type="danger"
            :disabled="!scope.row.activityName"
            @click="handleRefund(scope.row)"
          >
            退款
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 查看详情弹窗 -->
  <DetailModal
    ref="detailModalRef"
    @refresh="getList"
  />
</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import * as RefundActivityRecordApi from '@/api/mall/promotion/refund/activityRecord'
import type { RefundActivityRecordRespVO } from '@/api/mall/promotion/refund/activityRecord'
import DetailModal from './components/DetailModal.vue'

defineOptions({ name: 'RefundActivityRecord' })

const message = useMessage() // 消息弹窗
const router = useRouter() // 路由

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<RefundActivityRecordRespVO[]>([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  mobile: undefined,
  createTime: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RefundActivityRecordApi.getRefundActivityRecordPage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 导出按钮操作 */
const handleExport = () => {
  message.info('导出功能开发中...')
}

/** 查看操作 */
const detailModalRef = ref()
const handleView = (row: RefundActivityRecordRespVO) => {
  if (!row.activityName) {
    message.warning('该活动已被删除，无法查看详情')
    return
  }
  detailModalRef.value.open(row.id)
}

/** 退款操作 */
const handleRefund = async (row: RefundActivityRecordRespVO) => {
  if (!row.activityName) {
    message.warning('该活动已被删除，无法进行退款操作')
    return
  }

  if (!row.afterSaleId) {
    message.error('售后ID不存在，无法跳转')
    return
  }

  // 跳转到售后详情页面
  await router.push(`/mall/trade/after-sale/detail/${row.afterSaleId}`)
}

/** 获取阶段标签类型 */
const getStageTagType = (stage: number, activityUploadProof?: boolean, activityName?: string, hasClosed?: boolean) => {
  // 优先检查活动是否被删除
  if (!activityName) {
    return 'danger'
  }

  // 检查打卡是否已终止
  if (hasClosed === true) {
    return 'danger'
  }

  // 处理activityUploadProof为undefined或null的情况
  const needUploadProof = activityUploadProof === true

  // 如果不需要上传凭证，只有2个阶段
  if (!needUploadProof) {
    switch (stage) {
      case 1:
        return 'warning'
      case 2:
        return 'success' // 第2阶段就是完成状态
      default:
        // 对于未知阶段，根据数值范围给出合理的标签类型
        if (stage <= 0) {
          return 'info'
        } else if (stage > 2) {
          return 'success'
        } else {
          return 'danger'
        }
    }
  }

  // 需要上传凭证时，有更多阶段
  switch (stage) {
    case 1:
      return 'warning'
    case 2:
      return 'warning'
    case 3:
      return 'success'
    case 4:
      return 'success'
    default:
      // 对于未知阶段，根据数值范围给出合理的标签类型
      if (stage <= 0) {
        return 'info'
      } else if (stage > 4) {
        return 'success'
      } else {
        return 'danger'
      }
  }
}

/** 获取阶段文本 */
const getStageText = (stage: number, activityUploadProof?: boolean, activityName?: string, hasClosed?: boolean) => {
  // 优先检查活动是否被删除
  if (!activityName) {
    return '活动已删除'
  }

  // 检查打卡是否已终止
  if (hasClosed === true) {
    return '打卡已终止'
  }

  // 处理activityUploadProof为undefined或null的情况
  const needUploadProof = activityUploadProof === true

  // 如果不需要上传凭证，只有2个阶段
  if (!needUploadProof) {
    switch (stage) {
      case 1:
        return '进行中'
      case 2:
        return '已完成' // 第2阶段就是完成状态
      default:
        // 对于未知阶段，根据数值范围给出合理的文本
        if (stage <= 0) {
          return '未开始'
        } else if (stage > 2) {
          return '已完成'
        } else {
          return '未知阶段'
        }
    }
  }

  // 需要上传凭证时，有更多阶段
  switch (stage) {
    case 1:
      return '进行中'
    case 2:
      return '进行中'
    case 3:
      return '已完成'
    case 4:
      return '已完成'
    default:
      // 对于未知阶段，根据数值范围给出合理的文本
      if (stage <= 0) {
        return '未开始'
      } else if (stage > 4) {
        return '已完成'
      } else {
        return '未知阶段'
      }
  }
}

/** 获取打卡规则文本 */
const getPunchCardRuleText = (rule: number) => {
  switch (rule) {
    case 1:
      return '持续打卡'
    case 2:
      return '非持续打卡'
    case 3:
      return '无需打卡'
    default:
      return '未知'
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
